iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 14
0

這次要介紹的是Docker Compose的部分,為什這會需要Docker Compose,當想要佈署的Container數量太多時,在管理各服務之間關聯時,就會很不方便和麻煩。

Docker Compose是一個可以讓你透過指令控制多個Container,主要也是用YAML格式來去描述和定義各服務的關係,白話來說就是管理container的文件檔。

Docker Compose安裝

linux安裝docker-compose

sudo curl -L "https://github.com/docker/compose/releases/download/1.27.3/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose

sudo chmod +x /usr/local/bin/docker-compose

sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose

安裝完成

➜  ~ docker-compose --version
docker-compose version 1.27.2, build 18f557f9

不同系統如何安裝docker-compose,請參考安裝連結

建立docker-compose.yml

version: '3'
services:
    httpserver:
        image: httpserver:v1.0.1
        ports:
            - "8080:8080"
        depends_on:
            - grpcserver           
        links:
        - grpcserver    
        restart: always   
        container_name: hs   
    grpcserver:
        image: grpcserver:v1.0.0
        ports:
            - 8081:8081
        restart: always
        container_name: gs
  • container_name: 服務啟動後的名稱
  • depends_on: 服務啟動後會有先後順序問題,使用depends_on標籤可以解決容器的依賴,啟動時會先啟動gs(grpcserver)服務,最後才啟動hs(httpserver)
  • links: 和docker的 --link是相同效果,透過標籤解決容器連線問題

Docker Compose指令

使用docker-compose指令需要和docker-compose.yml同一層目錄。

啟動服務 - -d表示背景執行

docker-compose up -d 

查看執行的服務

docker-compose ps

結果

Name     Command      State           Ports
----------------------------------------------------
gs     ./grpcserver   Up      0.0.0.0:8081->8081/tcp
hs     ./httpserver   Up      0.0.0.0:8080->8080/tcp

查看執行服務的log

docker-compose logs

結果

Attaching to hs, gs
gs            | {"level":"info","msg":"grpc server start","time":"2020-09-19T07:44:09Z"}
gs            | {"level":"info","msg":"user add ok: a00017","time":"2020-09-19T07:44:34Z"}
gs            | {"level":"info","msg":"user login ok: a00017","time":"2020-09-19T07:44:45Z"}
gs            | {"level":"warning","msg":"user login password error: a00017","time":"2020-09-19T07:44:48Z"}
gs            | {"level":"warning","msg":"user login password error: a00017","time":"2020-09-19T07:45:53Z"}
gs            | {"level":"warning","msg":"user add failed: a00017","time":"2020-09-19T07:46:03Z"}
hs            | {"level":"info","msg":"http server start","time":"2020-09-19T07:44:10Z"}
hs            | {"err":"unexpected end of JSON input","level":"error","msg":"Error Log","time":"2020-09-19T07:46:45Z","trace":"userLogin_2"}

暫停服務

docker-compose stop

刪除服務

docker-compose rm

删除所有容器

//container會被停止,然後被刪除,建立的network也會被刪除
docker-compose down

結果

Stopping hs ... done
Stopping gs ... done
Removing hs ... done
Removing gs ... done
Removing network docker-compose_default

上一篇
Day13 Docker實戰
下一篇
Day15 Google Cloud Platform
系列文
微服務系統建置與監控30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言